package cn.kai.base.mapper;

import cn.kai.base.BaseDO;
import cn.kai.base.query.LambdaQuery;
import cn.kai.base.query.QueryHead;
import cn.kai.base.query.QueryTail;
import cn.kai.enums.BizCodeEnum;
import cn.kai.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;

import java.util.Map;

/**
 * 自定义的base mapper
 * Author: chenKai
 * Date: 2024/7/12
 */
public interface CustomBaseMapper<T extends BaseDO> extends BaseMapper<T> {
    /**
     * 校验唯一键
     * @param args
     * @param bizCodeEnum
     */
    default  void  checkUnique(Map<String,Object> args, BizCodeEnum bizCodeEnum){
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        args.forEach(wrapper::eq);
        Long count = this.selectCount(wrapper);
        if (count > 0){
            throw new BizException(bizCodeEnum);
        }
    }

    default <R> void  checkUnique(SFunction<T,R> sFunction, Object value, BizCodeEnum bizCodeEnum){
        LambdaQueryWrapper<T> wrapper = new QueryWrapper<T>().lambda();
        wrapper.eq(sFunction,value);
        Long count = this.selectCount(wrapper);
        if (count > 0){
            throw new BizException(bizCodeEnum);
        }
    }

    default <R> void  checkUnique(SFunction<T,R> sFunction, Object value, String errorMessage){
        LambdaQueryWrapper<T> wrapper = new QueryWrapper<T>().lambda();
        wrapper.eq(sFunction,value);
        Long count = this.selectCount(wrapper);
        if (count > 0){
            throw new BizException(BizCodeEnum.FAIL.getCode(),errorMessage);
        }
    }

    default void  checkUnique(LambdaQueryWrapper<T> wrapper, BizCodeEnum bizCodeEnum){
        Long count = this.selectCount(wrapper);
        if (count > 0){
            throw new BizException(bizCodeEnum);
        }
    }

    default QueryTail<T> where(){
        return new QueryTail<>(this,new LambdaQuery<>());
    }

    /**
     * 根据条件判断是否存在
     * @param wrapper
     * @return
     */
    default boolean isExist(LambdaQueryWrapper<T> wrapper){
        Long count = this.selectCount(wrapper);
        if (count > 0){
            return true;
        }else {
            return false;
        }
    }

    default QueryHead<T> select(){
        return new QueryHead<>(this);
    }

}
